package com.zzsy.carosshopprojects.base;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.king.base.util.ToastUtils;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
import com.yzy.voice.VoicePlay;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.common.RechargeSuccessAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.common.payresult.PayResultAc;
import com.zzsy.carosshopprojects.bean.BaseBean;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.HUD;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.view.TitleControlView;

import java.math.BigDecimal;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.ycbjie.ycstatusbarlib.bar.StateAppBar;
import cn.ycbjie.ycstatusbarlib.utils.StatusBarUtils;

/**
 * Activity的基类
 */
public abstract class BaseActivity extends AbActivity {
    private Unbinder unbinder;
    public final static int REQUEST_CODE = 1001;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            savedInstanceState.putParcelable("android:support:fragments", null);
        }
        super.onCreate(savedInstanceState);
        setContentView(bindLayout());
        ScreenAdapterTools.getInstance().loadView(getWindow().getDecorView());
        unbinder = ButterKnife.bind(this);
        initView();
        initData();
        loadMethod();
        setBarState();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    protected abstract int bindLayout();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void loadMethod();

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        super.onDestroy();
    }

    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            ActivityCompat.finishAfterTransition(this);
        }
    }

    /**
     * 设置标题头
     *
     * @param view
     */
    public void initTitle(View view, String title, FragmentActivity activity) {
        TitleControlView t = new TitleControlView(view, () -> goBack(activity));
        t.setTitle(title);
    }

    /**
     * 设置顶部状态栏颜色和字体颜色
     */
    public void setBarState() {
        StateAppBar.setStatusBarColor(this,
                ContextCompat.getColor(this,
                        R.color.white));
        //状态栏亮色模式，设置状态栏黑色文字、图标
        StatusBarUtils.StatusBarLightMode(this);

    }

    /**
     * 返回上一页
     *
     * @param activity
     */
    public void goBack(FragmentActivity activity) {
        if (activity.getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            ActivityCompat.finishAfterTransition(activity);
        }
    }

    /**
     * 获取vm实例
     *
     * @return
     */
    public ViewModelProvider getViewModelProvider() {
        return new ViewModelProvider(this,
                ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()));
    }

    /**
     * 跳转第三方银联刷卡支付的回调
     */
    @Override
    protected void onActivityResult(int requestCode, final int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        HUD.getInstance().dismiss();
        Log.d("xxxxx", "银行卡回调" + requestCode + "=====" + resultCode);
        if (requestCode == REQUEST_CODE) {
            // HUD.getInstance().dismiss();
//            HUD.getInstance().show(this, "正在响应结果...");
            if (data == null || "".equals(data)) {
                ToastUtils.showToast(getApplicationContext(), getResources().getString(R.string.noResult));
            } else {
                switch (resultCode) {
                    case AppCompatActivity.RESULT_CANCELED:
                        String reason = "";
                        try {
                            reason = data.getStringExtra("reason");
                            if (StringUtils.isEmpty(reason)) {
                                reason = getResources().getString(R.string.payFail);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            reason = getResources().getString(R.string.payFail);
                        }
                        String orderNumberFail = data.getStringExtra("orderNumber");
                        String feePayTypes = data.getStringExtra("type");
                        if (feePayTypes == null) {
                            feePayTypes = "";
                        }
                        String payDates = data.getStringExtra("date");
                        String typess = "";
                        if (orderNumberFail.contains("CZ")) {
                            typess = "4";
                        } else {
                            typess = "3";
                        }
                        ToastUtils.showToast(getApplicationContext(), reason + orderNumberFail);
                        // HUD.getInstance().dismiss();
                        getBankPayChannel(false, "", "", orderNumberFail, typess, feePayTypes, payDates);
                        break;
                    case AppCompatActivity.RESULT_OK:
                        String traceNo = data.getStringExtra("traceNo");
                        String orderNumber = data.getStringExtra("orderNumber");
                        String amount = data.getStringExtra("amount");
                        String feePayType = data.getStringExtra("type");
                        String payDate = data.getStringExtra("date");
                        String types;
                        if (orderNumber.contains("CZ")) {
                            types = "4";
                        } else {
                            types = "3";
                        }
                        getBankPayChannel(true, amount, traceNo, orderNumber, types, feePayType, payDate);
                        break;
                    default:
                        ToastUtils.showToast(getApplicationContext(), getApplicationContext().getResources().getString(R.string.payError));
                        //   HUD.getInstance().dismiss();
                        finish();
                        break;
                }

            }

        }
    }

    /**
     * 判断银联支付方式
     */
    private void getBankPayChannel(boolean isSuf, String amount, String traceNo, String orderNumber, String type, String feePayType, String payDate) {
        RequestUtils.BankPayChannel(this, DataUtil.getInstance().getStoreId(), type, new MyObserver<BaseBean>(this, true) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String DataMsg, int code) {
                if (code == ConfigureFile.code) {
                    String bankData = ConverterHelper.toBigDecimal(DataMsg).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
                    if ("1".equals(bankData)) {
                        if (isSuf) {
                            if (orderNumber.contains("CZ")) {
                                UpdateRecheargeOrderStatus(orderNumber, traceNo, amount, feePayType, payDate);
                            } else {
                                updateOrderState(isSuf, orderNumber, "1", "1", traceNo, amount, feePayType, payDate);
                            }
                        } else {
                            if (!orderNumber.contains("CZ")) {
                                updateOrderState(false, orderNumber, "2", "3", "", "", feePayType, payDate);
                            } else {
                                finish();
                            }
                        }
                    } else if ("2".equals(bankData)) {
                        if (isSuf) {
                            if (orderNumber.contains("CZ")) {
                                UpdateRecheargeOrderStatus(orderNumber, traceNo, amount, feePayType, payDate);
//                                MusicTell(amount);
//                                Intent intents = new Intent(BaseActivity.this, BaseActivity.class);
//                                intents.putExtra("orderNumber", orderNumber);
//                                startActivity(intents);
//                                finish();
                            } else {
                                //进行语音播报
                                if (!StringUtils.isEmpty(amount)) {
                                    MusicTell(amount);
                                }
                                PayResultAc.start(BaseActivity.this, orderNumber, "200", amount, "0");
                                finish();
                            }
                        } else {
                            finish();
                        }
                    }
                } else {
                    HUD.getInstance().dismiss();
                    ToastUtils.showToast(getApplicationContext(), DataMsg);
                    finish();
                }
            }
        });
    }

    /**
     * 更改订单状态
     */
    private void UpdateRecheargeOrderStatus(String orderNumber, String out_trade_no, String amount, String feePayType, String payDate) {
        RequestUtils.UpdateRecheargeOrderStatus(BaseActivity.this, orderNumber, out_trade_no, feePayType, payDate, new MyObserver<BaseBean>(BaseActivity.this, true) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                HUD.getInstance().dismiss();
                if (code == ConfigureFile.code) {
                    //进行语音播报
                    MusicTell(amount);
                    RechargeSuccessAc.start(BaseActivity.this, orderNumber);
                } else {
                    finish();
                    ToastUtils.showToast(getApplicationContext(), errorMsg);
                }
                finish();
            }
        });

    }

    /**
     * 更改订单状态
     *
     * @param bankPayNum
     * @param orderNumber
     * @param payStatus
     * @param orderStatus
     */
    private void updateOrderState(boolean isSuf, String orderNumber, String payStatus, String orderStatus, String bankPayNum, String amount, String feePayType, String payDate) {
        RequestUtils.UpdateOrderStatus(BaseActivity.this, bankPayNum, orderNumber, orderStatus, payStatus, feePayType, payDate, new MyObserver<BaseBean>(BaseActivity.this, true) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                HUD.getInstance().dismiss();
                if (code == ConfigureFile.code) {
                    if (isSuf) {
                        //进行语音播报
                        if (!StringUtils.isEmpty(amount)) {
                            MusicTell(amount);
                        }
                        PayResultAc.start(BaseActivity.this, orderNumber, "200", amount, "0");
                        finish();
                    } else {
                        Log.d("xxxaaa",   "333====");
                        ToastUtils.showToast(getApplicationContext(), getApplicationContext().getResources().getString(R.string.payFail));
                        finish();
                    }
                } else {
                    Log.d("xxxaaa",   "444====");
                    ToastUtils.showToast(getApplicationContext(), errorMsg);
                    finish();
                }
            }
        });
    }

    /**
     * 进行语音播报
     */
    private void MusicTell(String payAmount) {
        String amounts = ConverterHelper.toBigDecimal(payAmount).divide(ConverterHelper.toBigDecimal(100)).toString();
        VoicePlay.with(BaseActivity.this).play(amounts, false);
    }

}
